//
//  YAStatusVM.swift
//  KeepCliming
//
//  Created by 鱼龙之梦 on 15/9/6.
//  Copyright © 2015年 panyanzhi. All rights reserved.
//

import UIKit
import SDWebImage
class YAStatusVM: NSObject {
    var status:YAStatus
    //MARK:--- 将数据模型中的路径字符串转化成URL
    var userIconURL:NSURL?{
        return NSURL(string: status.user?.profile_image_url ?? "")
    }
    var cellId:String{
        return status.retweeted_status != nil ? YAStatusForwardCellID:YAStatusNormalCellID
    }
    //MARK:--- 将数据模型中的认证类型翻译成对应图标
    var userVipImage:UIImage?{
        if (status.user?.verified == 1) {
            switch(status.user?.verified ?? -1){
            case 1:return UIImage(named: "avatar_vip")
            case 2,3,5: return UIImage(named: "avatar_enterprise_vip")
            case 220 :return UIImage(named: "avatar_grassroot")
            default: return nil
            }
        }
        return nil
    }
    //MARK:--- 将数据模型中的等级数据翻译成对应图标
    var userMemberImage:UIImage?{
        if status.user?.mbrank > 0 && status.user?.mbrank < 7 {
            return UIImage(named: "common_icon_membership_level\(status.user!.mbrank)")
        }
        return nil
    }
    //MARK:--- 缩略图URL数组
    var thumbnailURLs:[NSURL]?
     //MARK:--- 中型图片数组
    var bmiddleURLs:[NSURL]?{
        guard let urls = thumbnailURLs else
        {
            return nil
        }
        //按顺序替换缩略图里URL路径为中型图的URL
        var array = [NSURL]()
        for url in urls{
            let urlString = url.absoluteString.stringByReplacingOccurrencesOfString("/thumbnail/", withString: "/bmiddle/")
            array.append(NSURL(string: urlString)!)
        }
        return array
    }
    //转发微博文字
    var forwordText:String?{
        let userName = status.retweeted_status?.user?.name ?? ""
        let text = status.retweeted_status?.text ?? ""
        return "@"+userName + ":" + text
    }
    //MARK:--- 行高
    var rowHeight:CGFloat = 0
    //MARK:--- 构造函数
    init(status:YAStatus) {
        self.status = status
        //不是转发就是原创图片
        if let urls = status.retweeted_status?.pic_urls ?? status.pic_urls{
            thumbnailURLs = [NSURL]()
            for dict in urls{
                thumbnailURLs?.append(NSURL(string: dict["thumbnail_pic"]!)!)
            }
        }
        super.init()
    }
    override var description:String{
        return self.status.description + " 缩略图数组\(thumbnailURLs)"
    }
}
import ReactiveCocoa
//MARK:--- 分离网络方法,获取网络数据
class YAStatusListVM:NSObject
{
    //注意：这里不能直接写YAStatus类型
    lazy var statues:[AnyObject]=[YAStatusVM]()
    func loadStatues(isPull isPull:Bool)->RACSignal{
        //默认下拉
        var since_id = (statues.count ?? 0) == 0 ? 0 : (statues.first as! YAStatusVM).status.id
        var max_id = 0
        
        if isPull {//上推//加载历史数据
            since_id = 0
            max_id = (statues.last as! YAStatusVM).status.id - 1
        }
        
        return RACSignal.createSignal({ (subscriber) -> RACDisposable! in
            
            YAStatusDAL.loadStatues(since_id, max_id: max_id, completion: { (result) -> () in
                //注意：数据里含有字典的写法：[[NSString:AnyObject]]，guard的用法
                if result == nil {
                    printLog("没有获取到正确的数据")
                    return
                }
                //为了保证当前数据不被覆盖掉，定义一个临时数组记录当前网络请求返回的结果
                var arrayM = [AnyObject]()
                for dict in result! {
                    arrayM.append(YAStatusVM(status: YAStatus(dict: dict)))
                }
                printLog("加载到\(arrayM.count)数据")
                self.chcheWebImgage(arrayM as! [YAStatusVM]) {
                    if max_id == 0{//加载最新数据
                        self.statues = arrayM + self.statues
                    }else if since_id == 0 {
                        self.statues = self.statues + arrayM
                    }
                    //注意：通知调用方已经加载完成，不必返回，因为已经存储在这个类的数组变量里了
                    // 如果是下拉刷新，提示用户
                    if since_id > 0 {
                        // RAC 是 OC 的，通知订阅者，下拉刷新的数据
                        subscriber.sendNext(arrayM.count)
                    }
                    subscriber.sendCompleted()
                }

            })
            return nil
        })
    }
    ///  当从获取网络数据生成视图模型数组后，将传入这个数组进行缩略图路径过滤，对单张进行缓存
    ///  当所有数组数据过滤完后，返回一个执行回调闭包，发送信号
    ///  :param: array    视图模型数组
    ///  :param: finished 回调闭包
    private func chcheWebImgage(array:[YAStatusVM],finished:()->()){
        let group = dispatch_group_create()
        var dataLegth = 0
        for vm in array{
            let count = vm.thumbnailURLs?.count ?? 0
            if count != 1 {
                continue
            }
            //  printLog(vm.thumbnailURLs)
            //入组
            dispatch_group_enter(group)
            //注意：缓存网络图片核心方法
            SDWebImageManager.sharedManager().downloadImageWithURL(vm.thumbnailURLs![0], options: [], progress: nil, completed: { (image, _, _, _, _) -> Void in
                if image != nil {
                    let data = UIImagePNGRepresentation(image)
                    dataLegth += data?.length ?? 0
                }
                //出组
                dispatch_group_leave(group)
            })
        }
        dispatch_group_notify(group, dispatch_get_main_queue()) {
            printLog("缓存图片完成\(dataLegth/1024)K")
            finished()//执行调用者传来的闭包
            let path = NSSearchPathForDirectoriesInDomains( NSSearchPathDirectory.DocumentDirectory,NSSearchPathDomainMask.UserDomainMask, true).last
            printLog(path)
        }
    }
}